import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess
} from 'Shared/actions/currentUserContext';
import {uuid} from '../utils';
import {PAGE_CODE} from './constants';
import * as api from './api';
import moment from 'moment';
import {uniq, maxBy} from 'lodash';
import {partOrderPriceTerms} from '../Enum';

export const GET_INIT_DATA_BEGIN = 'GET_INIT_DATA_BEGIN';
export const GET_INIT_DATA_SUCCESS = 'GET_INIT_DATA_SUCCESS';
export const GET_INIT_DATA_FAIL = 'GET_INIT_DATA_FAIL';

const getInitDataBegin = () => ({
    type: GET_INIT_DATA_BEGIN
});

const getInitDataSuccess = data => ({
    type: GET_INIT_DATA_SUCCESS,
    data
});
const getInitDataFail = () => ({
    type: GET_INIT_DATA_FAIL
});

//*==============================初始化API================================= */
export const getInitData = (code = PAGE_CODE) => dispatch => {
    dispatch(getInitDataBegin());
    const init = api.getInitData().then(res => {
        if(res.ok)
            dispatch(getInitDataSuccess(res.data));
        else
            dispatch(getInitDataFail());
        return res.ok;
    });
    const permissions = getCurrentUserPagePermissionsApi(code).then(res => {
        if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });
    return Promise.all([init, permissions]).then(values => values[0] && values[1]);
};
/*==============================查询列表================================= */

export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';
export const getListBegin = () => ({
    type: GET_LIST_BEGIN
});
export const getListSuccess = (data, condition) => ({
    type: GET_LIST_SUCCESS,
    data,
    condition
});
export const getListFail = () => ({
    type: GET_LIST_FAIL,
}); //获取列表

export const getList = condition => dispatch => {
    dispatch(getListBegin());
    const {dealerCode, dealerName, invoicedDate, ...props} = condition;
    if(invoicedDate && invoicedDate.length > 0) {
        props.beginInvoicedDate = moment(invoicedDate[0]).toISOString();
        props.endInvoicedDate = moment(invoicedDate[1]).toISOString();
    }
    return api.getList(props).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
        return res.ok;
    });
}; //按钮搜索

//获取历史数据列表

export const GET_HISTORY_LIST_BEGIN = 'GET_HISTORY_LIST_BEGIN';
export const GET_HISTORY_LIST_SUCCESS = 'GET_HISTORY_LIST_SUCCESS';
export const GET_HISTORY_LIST_FAIL = 'GET_HISTORY_LIST_FAIL';
export const getHistoryListBegin = () => ({
    type: GET_HISTORY_LIST_BEGIN
});
export const getHistoryListSuccess = (data, condition) => ({
    type: GET_HISTORY_LIST_SUCCESS,
    data,
    condition
});
export const getHistoryListFail = () => ({
    type: GET_HISTORY_LIST_FAIL,
}); //获取列表

export const getHistoryList = condition => dispatch => {
    dispatch(getHistoryListBegin());
    const {dealerCode, dealerName, invoicedDate, ...props} = condition;
    if(invoicedDate && invoicedDate.length > 0) {
        props.beginInvoicedDate = moment(invoicedDate[0]).toISOString();
        props.endInvoicedDate = moment(invoicedDate[1]).toISOString();
    }
    return api.getHistoryList(props).then(res => {
        if(res.ok)
            dispatch(getHistoryListSuccess(res.data, condition));
        else
            dispatch(getHistoryListFail());
        return res.ok;
    });
};

export const querySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    return dispatch(getList(condition));
};
//按钮搜索历史
export const queryHistorySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'historyQueryCondition'])
        .toJS();
    return dispatch(getHistoryList(condition));
};

//分页排序搜索

export const tableSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    return dispatch(getList(condition));
};

export const tableHistorySearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'historyQueryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    return dispatch(getHistoryList(condition));
};


/*=============================作废================================= */
export const onClickAbandon = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.abandonInfo(id, {
        rowVersion
    }).then(res => res.ok);
};

/* =======================详情页作废================================== */
export const onClickAbandonForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.abandonInfo(id, {
        rowVersion
    });
};


/*=============================关闭================================= */
export const onClickUploadSAP = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.uploadSAPInfo(id, {
        rowVersion
    }).then(res => res.ok);
};

/* =======================详情页关闭================================== */
export const onClickUploadSAPForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.uploadSAPInfo(id, {
        rowVersion
    });
};
/*==============================查询action================================= */
//修改查询条件

export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
//修改历史查询条件
export const SAVE_HISTORY_QUERY_CONDITION = 'SAVE_HISTORY_QUERY_CONDITION';
export const saveHistoryQueryCondition = (name, value) => ({
    type: SAVE_HISTORY_QUERY_CONDITION,
    name,
    value
});
//重置查询条件

export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});
//重置发票历史查询条件
export const RESET_HISTORY_QUERY_PANEL = 'RESET_HISTORY_QUERY_PANEL';
export const resetHistoryQueryPanel = () => ({
    type: RESET_HISTORY_QUERY_PANEL,
});

/* =======================获取详情================================== */
export const GET_DETAIL_BEGIN = 'GET_DETAIL_BEGIN';
export const GET_DETAIL_SUCCESS = 'GET_DETAIL_SUCCESS';
export const GET_DETAIL_FAIL = 'GET_DETAIL_FAIL';
export const getDetailBegin = () => ({
    type: GET_DETAIL_BEGIN
});
export const getDetailSuccess = data => ({
    type: GET_DETAIL_SUCCESS,
    data
});
export const getDetailFail = () => ({
    type: GET_DETAIL_FAIL,
});

/*==============================清除数据================================= */
export const CLEAR_DATA = 'CLEAR_DATA';
export const clearData = () => ({
    type: CLEAR_DATA
});

export const onClickUpdate = id => (dispatch, getState) => {
    const {
        dealerId,
        brandId,
        buyer,
        buyerAddress,
        buyerNumber,
        buyerFAX,
        buyerCantact,
        seller,
        sellerAddress,
        sellerNumber,
        sellerFAX,
        origin,
        destination,
        paymentType,
        priceTerms,
        shipmentType,
        freight,
        insurance,
        discountAmount,
        otherAmount,
        claimAmount,
        isBonusNumber,
        differentAmount,
        discountReason,
        packingLists = [],
        isCoerciveBonus,
        rowVersion,
        carrierId,
        rebateFee
    } = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    const isBonus = typeof isBonusNumber === 'number' ? Boolean(isBonusNumber) : isBonusNumber;
    if(id)
        return api.updateInfo(id, {
            buyer,
            buyerAddress,
            buyerNumber,
            buyerFAX,
            buyerCantact,
            seller,
            sellerAddress,
            sellerNumber,
            sellerFAX,
            origin,
            destination,
            paymentType,
            priceTerms,
            shipmentType,
            freight,
            insurance,
            discountAmount,
            otherAmount,
            claimAmount,
            differentAmount,
            isBonus,
            discountReason,
            isCoerciveBonus,
            carrierId,
            rebateFee,
            packingLists: packingLists.map(item => ({
                id: item.id,
                rowVersion: item.rowVersion
            })),
            rowVersion,
        });
    return api.addInfo({
        dealerId,
        brandId,
        buyer,
        buyerAddress,
        buyerNumber,
        buyerFAX,
        buyerCantact,
        seller,
        sellerAddress,
        sellerNumber,
        sellerFAX,
        origin,
        destination,
        paymentType,
        priceTerms,
        shipmentType,
        freight,
        insurance,
        discountAmount,
        otherAmount,
        claimAmount,
        differentAmount,
        isBonus,
        discountReason,
        isCoerciveBonus,
        carrierId,
        rebateFee,
        packingLists: packingLists.map(item => ({
            id: item.id,
            rowVersion: item.rowVersion
        })),
    });
};

export const SELECT_DATA = 'SELECT_DATA';
export const selectData = data => ({
    type: SELECT_DATA,
    data
});
/*==========================修改新增编辑页数据================================= */
export const SAVE_SUBMIT_CONDITION = 'SAVE_SUBMIT_CONDITION';

export const saveSubmitCondition = (name, value) => ({
    type: SAVE_SUBMIT_CONDITION,
    name,
    value
});

export const savePriceTermsCondition = (name, value) => dispatch => {
    if(value === partOrderPriceTerms.CPT || value === partOrderPriceTerms.CFR)
        dispatch(selectData({insurance: 0}));
    else if(value === partOrderPriceTerms.FOB ||
        value === partOrderPriceTerms.FCA || value === partOrderPriceTerms.EXW)
        dispatch(selectData({
            freight: 0,
            insurance: 0
        }));
    return dispatch({
        type: SAVE_SUBMIT_CONDITION,
        name,
        value
    });
};

export const selectCoerciveBonus = () => dispatch => dispatch(selectData({
    isCoerciveBonus: true,
    isBonusNumber: Number(true)
}));

export const SELECT_DEALER_QUERY = 'SELECT_DEALER_QUERY';
export const selectDealer = data => ({
    type: SELECT_DEALER_QUERY,
    data: {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
    }
});

export const SELECT_HISTORY_DEALER_QUERY = 'SELECT_HISTORY_DEALER_QUERY';
export const selectHistoryDealer = data => ({
    type: SELECT_HISTORY_DEALER_QUERY,
    data: {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
    }
});


export const selectCountry = data => dispatch => dispatch(selectData({
    dealerId: data.id,
    dealerCode: data.code,
    dealerName: data.name,
    receiverCode: data.arrivedDealerCode,
    country: data.countryName,
    currency: data.currency,
    seller: data.seller,
    sellerAddress: data.sellerAddress,
    sellerNumber: data.sellerNumber,
    sellerFAX: data.sellerFAX,
    contactPhone: data.contactPhone,
    buyer: '',
    buyerAddress: '',
    buyerNumber: '',
    buyerFAX: '',
    buyerCantact: '',
    origin: '',
    destination: '',
    details: [],
    packingLists: [],
}));

export const SELECT_DETAILS = 'SELECT_DETAILS';
export const selectDetails = (data, result) => ({
    type: SELECT_DETAILS,
    data,
    result
});

export const DELETE_DETAIL = 'DELETE_DETAIL';
export const deleteDetail = id => ({
    type: DELETE_DETAIL,
    id
});
export const DELETE_ALL_DETAIL = 'DELETE_ALL_DETAIL';
export const deleteAllDetail = () => ({
    type: DELETE_ALL_DETAIL
});


export const SELECT_INVOICE_DETAILS = 'SELECT_INVOICE_DETAILS';
export const selectInvoiceDetails = data => ({
    type: SELECT_INVOICE_DETAILS,
    data
});

export const selectPacking = data => dispatch => {
    const result = [];
    const conditions = data.map(item => {
        const {details = []} = item;
        const packingDetails = details.map(p => ({
            packingListId: item.id,
            id: p.id,
            packingListCode: item.code,
            partSaleOrderCode: p.partSaleOrderCode,
            partCode: p.partCode,
            partName: p.partName,
            quantity: p.quantity,
            price: p.price,
            pricingDate: p.pricingDate,
            totalAmount: p.totalAmount,
            perNetWeight: p.perNetWeight,
            netWeight: p.netWeight,
            perGrossWeight: p.perGrossWeight,
            grossWeight: p.grossWeight,
            oldPartCode: p.oldPartCode,
            oldPartName: p.oldPartName,
            pickingListCode: p.pickingListCode,
            palletCode: p.palletCode
        }));
        result.push(...packingDetails);
        return {
            id: item.id,
            code: item.code,
            packingType: item.packingType,
            container: item.container,
            length: item.length,
            width: item.width,
            height: item.height,
            volume: item.volume,
            netWeight: item.netWeight,
            grossWeight: item.grossWeight,
            containerNo: item.containerNo,
            remark: item.remark,
            pickingListCodes: item.pickingListCodes,
            palletCode: item.palletCode,
            palletCodes: item.palletCodes,
            rowVersion: item.rowVersion
        };
    });
    dispatch(selectDetails(conditions, result));
};

export const getPrevInfo = () => (dispatch, getState) => {
    const {dealerId} = getState().getIn(['page', 'appState', 'submitData']).toJS();
    return api.getPrevList({
        dealerId,
    }).then(res => {
        if(res.ok) {
            const {content = []} = res.data;
            const {buyer, buyerAddress, buyerNumber, buyerFAX, buyerCantact, origin, destination} = content[0] || {};
            dispatch(selectData({
                buyer,
                buyerAddress,
                buyerNumber,
                buyerFAX,
                buyerCantact,
                origin,
                destination,
            }));
        }
        return res.ok;
    });
};

export const getPaymentType = () => (dispatch, getState) => {
    const {details = []} = getState().getIn(['page', 'appState', 'submitData']).toJS();
    return api.getPaymentType({
        codes: uniq(details.map(item => item.partSaleOrderCode)),
    }).then(res => {
        if(res.ok) {
            const {paymentType, priceTerms, shipmentType} = res.data;
            dispatch(selectData({
                paymentType,
                priceTerms,
                shipmentType,
            }));
        }
        return res.ok;
    });
};

export const getRebateFee = () => (dispatch, getState) => {
    const {dealerId} = getState().getIn(['page', 'appState', 'submitData']).toJS();
    return api.getRebateFee({
        dealerId
    }).then(res => {
        if(res.ok) {
            const {rebateFee} = res.data;
            dispatch(selectData({
                rebateFee: rebateFee || 0
            }));
        }
        return res.ok;
    });
};

export const getLockedFee = orderId => (dispatch, getState) => {
    const {dealerId} = getState().getIn(['page', 'appState', 'submitData']).toJS();
    return api.getLockedFee({
        dealerId,
        orderId
    }).then(res => {
        if(res.ok) {
            const {lockedFee} = res.data;
            dispatch(selectData({
                lockedFee: lockedFee || 0
            }));
        }
        return res.ok;
    });
};

export const getFee = orderId => dispatch => Promise.all([dispatch(getLockedFee(orderId)), dispatch(getRebateFee())]).then(values => values[0] && values[1]);

export const getDetail = id => dispatch => {
    dispatch(getDetailBegin());
    return api.getDetail(id).then(res => {
        if(res.ok) {
            const {details = [], isBonus} = res.data;
            const newDetails = details.map(item => ({
                ...item,
                id: uuid(),
            }));
            dispatch(getDetailSuccess({
                ...res.data,
                isBonusNumber: typeof isBonus === 'boolean' ? Number(isBonus) : isBonus,
                details: newDetails,
            }));
        } else
            dispatch(getDetailFail());
        return res.ok;
    });
};
